//
//  AouthViewController.swift
//  SinaWeibo
//
//  Created by yang on 15/11/9.
//  Copyright © 2015年 yang. All rights reserved.
//

import UIKit
import SVProgressHUD
class AouthViewController: UIViewController {
    
    //关闭web
    @objc func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    //自动填充账号密码
    @objc func fullAccount(){
        let jsString = "document.getElementById('userId').value='542846574@qq.com',document.getElementById('passwd').value='yang910210'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    let webView = UIWebView()
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadAouthPage()
    }
    override func viewDidDisappear(animated: Bool) {
        super.viewDidAppear(animated)
        SVProgressHUD.dismiss()
    }
    //设置 UI 界面
    private func setupUI(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")
    }
    //请求用户授权Token
    private func loadAouthPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
}
//UIWebViewDelegate的代理
extension AouthViewController :UIWebViewDelegate{
    
    func webViewDidStartLoad(webView: UIWebView){
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView){
        SVProgressHUD.dismiss()
    }
    //获取code
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        if urlString.hasPrefix("https://api.weibo.com"){
            return true
        }
        if !urlString.hasPrefix(redirect_uri){
            return false
        }
        
        guard let query = request.URL?.query else {
            
            return false
        }
        
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        UserAccountViewModel().loadAccessToken(code) { (error) -> () in
            if error != nil {
                SVProgressHUD.showInfoWithStatus("网络君正在睡觉,请稍后再来")
                return
            }
         self.dismissViewControllerAnimated(false , completion: { () -> Void in
            NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewControler, object: "Welcome")
         })
        }
        return true
    }
        
}